'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.fnKeyPathSet = exports.fnKeyPathGet = undefined;

var _toConsumableArray2 = require('babel-runtime/helpers/toConsumableArray');

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _set = require('lodash/set');

var _set2 = _interopRequireDefault(_set);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var genFnReg = function genFnReg(fnNames) {
    return new RegExp('(' + fnNames + ')\\((.*?)\\)');
};
var genFnExecReg = function genFnExecReg(fnNames) {
    return new RegExp('.(' + fnNames + ')\\((.*?)\\)');
};

var getArgs = function getArgs(str) {
    if (!str) {
        return [];
    }
    return str.split(',');
};

var fnKeyPathGet = exports.fnKeyPathGet = function fnKeyPathGet(obj, keyPath, reg) {
    var rst = {
        result: obj,
        prev: null
    };
    if (!keyPath) {
        return rst;
    }
    var _reg = typeof reg == 'string' ? genFnReg(reg) : reg;
    var keys = keyPath.split('.');
    var result = obj;
    var prev = null;
    var key = void 0;
    for (var i = 0, il = keys.length; i < il; i++) {
        key = keys[i];
        var match = key.match(_reg);

        prev = result;
        if (!match) {
            result = result[key];
        } else {
            var _result;

            result = (_result = result)[match[1]].apply(_result, (0, _toConsumableArray3.default)(getArgs(match[2])));
        }
    }
    return {
        result: result,
        prev: prev,
        lastKey: key
    };
};

var fnKeyPathSet = exports.fnKeyPathSet = function fnKeyPathSet(obj, map, fnNames) {
    var reg = genFnReg(fnNames);
    for (var key in map) {
        if (!reg.test(key)) {
            (0, _set2.default)(obj, key, map[key]);
            continue;
        }

        var _fnKeyPathGet = fnKeyPathGet(obj, key, reg),
            result = _fnKeyPathGet.result,
            prev = _fnKeyPathGet.prev,
            lastKey = _fnKeyPathGet.lastKey;

        if (!prev) {
            continue;
        }
        prev[lastKey] = map[key];
    }
};
exports.default = fnKeyPathSet;